package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/*
服务端的完善，

 */
public class ServerPlus {
    private ServerSocket serverSocket;

    public ServerPlus(){
        try {
            serverSocket = new ServerSocket(9090);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while (true) {
                System.out.println("等待连接");
                Socket socket = serverSocket.accept();
                System.out.println("连接成功");
                Runnable r = new threadTest(socket);
                Thread t = new Thread(r);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        ServerPlus sp = new ServerPlus();
        sp.start();
    }

    private  class threadTest implements Runnable{
        private Socket socket;
        private String name;
        public threadTest(Socket socket){
            this.socket=socket;
            this.name=socket.getInetAddress().getHostName();
        }
        @Override
        public void run() {
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String temp;
                while ((temp = br.readLine())!=null){
                    System.out.println(temp);
                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
